<?php
// JANUS config includes
require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/config/config.php';

// Facebook SDK includes
require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/fb_php_sdk/src/facebook.php';

/**
 * Various Facebook-related functions for JANUS Facebook application
 */
class JanusFacebook {

	/**
	 * Checks for a signed session for the current user of the application.
	 * 
	 * If there is no session this function will print the markup to
	 * send the user to the Facebook 'Request for permissions' page for
	 * the application. If the session is present then this function will
	 * return the session object.
	 * 
	 * @param Facebook $facebook Facebook Application instance object
	 */
	public static function checkSessionAuth(Facebook $facebook)
	{
		$session = $facebook->getSession();
		
		if (!$session)
		{
			JanusFacebook::sendUserToLoginUrl($facebook);
		}
		else
		{
			return $session;
		}
	}
	
	/**
	 * Checks whether the Facebook API is accessible for the user for the current session.
	 * 
	 * Attempts a basic API call and if it fails then sends the user to authorise the app.
	 * @param Facebook $facebook Facebook Application instance object
	 */
	public static function checkApiAccess(Facebook $facebook)
	{
		try
		{
			$application = $facebook->api('/me');
		}
		catch (FacebookApiException $e)
		{
			error_log($e);
			JanusFacebook::sendUserToLoginUrl($facebook);
		}
	}
	
	/**
	 * Attempts to retrieve the Facebook cookie details for the current user of the specified application
	 * 
	 * See: http://developers.facebook.com/docs/authentication/ for the original code
	 * from the Facebook developers documentation
	 * 
	 * @param $appId Facebook application ID
	 * @param $applicationSecret Facebook application secret
	 */
	public static function getFacebookCookie($appId, $applicationSecret) {
		$args = array();
		parse_str(trim($_COOKIE['fbs_' . $appId], '\\"'), $args);
		ksort($args);
		$payload = '';
		foreach ($args as $key => $value) {
			if ($key != 'sig') {
				$payload .= $key . '=' . $value;
			}
		}
		if (md5($payload . $applicationSecret) != $args['sig']) {
			return null;
		}
		return $args;
	}
	
	/**
	 * Outputs the markup to send the user to the login url for the app
	 * @param Facebook $facebook Facebook Application instance object
	 */
	public static function sendUserToLoginUrl(Facebook $facebook)
	{
		// http://www.phpfour.com/blog/2010/05/quick-start-on-new-facebook-php-sdk-iframe-based/
		$url = $facebook->getLoginUrl(array(
			'canvas' => 1,
			'fbconnect' => 0,
			'cancel_url' => $GLOBALS['FACEBOOK']['CANVAS_PAGE'] . 'about.php'
		));

		echo "<html><body><script type='text/javascript'>top.location.href = '$url';</script></body></html>";
		exit();
	}
}
?>